package com.android.myipc.soket;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.android.myipc.R;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Android Studio.
 * User: pengym
 * Date: 2020/11/12
 * Time: 15:31
 * Name: 作用类：
 */
public class TCPActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int MESSAGE_RECEIVE_NEW_MSG = 1;
    private static final int MESSAGE_SOCKET_CONNECTED = 2;
    private TextView mButtom;
    private TextView mMessageTextView;
    private EditText mMessageEditText;
    private PrintWriter mPrintWriter;
    private Socket mClientSocket;
    //接受消息
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_RECEIVE_NEW_MSG:
                    mMessageTextView.setText(mMessageTextView.getText() +  (String)msg.obj);
                    break;
                case MESSAGE_SOCKET_CONNECTED:
                    mButtom.setEnabled(true);
                    break;
                default:
                    break;
            }
        }
    };

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButtom = findViewById(R.id.btn_text);
        mMessageEditText = findViewById(R.id.edit_text);
        mMessageTextView = findViewById(R.id.tv_text);
        mButtom.setOnClickListener(this);
        Intent service = new Intent(this, TCPService.class);
        startService(service);
        new Thread() {
            @Override
            public void run() {
                connectTCPServer();
            }
        }.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_text:
//                new Thread(net).start();
                final String msg = mMessageEditText.getText().toString();
                if (!TextUtils.isEmpty(msg) && mPrintWriter != null) {
                    mPrintWriter.println(msg);//将msg打印出来
                    mMessageEditText.setText("");
                    String time = formatDateTime(System.currentTimeMillis());
                    final String showedMsg = "self " + time + ":" + msg + "\n";
                    mMessageTextView.setText(mMessageTextView.getText() + showedMsg);
                }
        }
    }

    Runnable net = new Runnable() {
        @Override
        public void run() {
            final String msg = mMessageEditText.getText().toString();//将值给msg
            if (!TextUtils.isEmpty(msg) && mPrintWriter != null) {//判断msg是否为空
                mPrintWriter.println(msg);//将msg打印出来
//                String time = formatDateTime(System.currentTimeMillis());
//                final String showedMsg = "self " + time + ":" + msg + "\n";
//                mMessageTextView.setText(mMessageTextView.getText() + showedMsg);
            }
        }
    };

    @SuppressLint("SimpleDateFormat")
    private String formatDateTime(long currentTimeMillis) {
        return new SimpleDateFormat("(HH:mm:ss)").format(new Date(currentTimeMillis));
    }

    @Override
    protected void onDestroy() {
        if (mClientSocket != null) {
            try {
                mClientSocket.shutdownInput();
                mClientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }

    private void connectTCPServer() {
        Socket socket = null;
        while (socket == null) {
            try {
                socket = new Socket("192.168.10.100", 8688);
                System.out.println(socket.isConnected());
                mClientSocket = socket;
                mPrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);//通过BufferedWriter写入字符，为true则刷新缓冲区
                mHandler.sendEmptyMessage(MESSAGE_SOCKET_CONNECTED);
                System.out.println("connect server success");
            } catch (IOException e) {
                SystemClock.sleep(1000);
                System.out.println("connect tcp server failed , tetry...");
            }
        }
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (!TCPActivity.this.isFinishing()) {
                String msg = bufferedReader.readLine();
                System.out.println("receive :" + msg);
                if (msg != null) {
                    String time = formatDateTime(System.currentTimeMillis());
                    final String showedMsg = "server " + time + ":" + msg + "\n";
                    mHandler.obtainMessage(MESSAGE_RECEIVE_NEW_MSG, showedMsg).sendToTarget();
                }
            }
            System.out.println("quit...");
            mPrintWriter.close();
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}